
import 'dart:convert';

import 'package:data_table_2/data_table_2.dart';
import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:yuellyfactory/util/MathUtil.dart';
import '../../eventbus/EventBusUtil.dart';
import '../../eventbus/EventRefreshBase.dart';
import '../../util/BaseRequest.dart';
import '../../util/ColorUtil.dart';
import '../../util/ToastUtil.dart';
import '../../util/ViewUtil.dart';
import '../dto/PriceParm.dart';
import '../dto/PricePart.dart';
import '../dto/PriceRule.dart';


class MaterialEditParmVC extends StatefulWidget {

  final VoidCallback callback;
  final PricePart pricePart;
  const MaterialEditParmVC({super.key, required this.callback, required this.pricePart});

  @override
  State<MaterialEditParmVC> createState() => _MaterialEditParmVCState();
}

class _MaterialEditParmVCState extends State<MaterialEditParmVC> {

  final popoverController = ShadPopoverController();
  final formKey = GlobalKey<ShadFormState>();
  var specsList=[];

  final dialogKey = GlobalKey<ShadFormState>();

  PricePart pricePart=PricePart();
  PricePart parmPart=PricePart();
  Map parmValues={};
  Map remarkValues={};
  String ruleStr="";
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    if(widget.pricePart.spec.isNotEmpty){
      specsList=jsonDecode(widget.pricePart.spec);
    }
    ruleStr=widget.pricePart.rule;
    pricePart=widget.pricePart;

    if(pricePart.parmData.isNotEmpty){
      List list=jsonDecode(pricePart.parmData);
      for(var item in list){
        parmValues[item["name"]]=item["value"];
      }
    }
    if(pricePart.remarkData.isNotEmpty){
      List list=jsonDecode(pricePart.remarkData);
      for(var item in list){
        remarkValues[item["name"]]=item["value"];
      }
    }
    getParms();

  }

  void getParms(){
    BaseRequest.postHttp('price/typeparmbyid',parameters: {"id":widget.pricePart.parentId}, canTip: true, context: context, onSuccess: (data){
      dynamic datas=data["data"];
      var part=PricePart.fromJson(datas);
      parmPart=part;
      setState(() {

      });
    }, onError: (error){});
  }

  @override
  void dispose() {

    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return
      ShadSheet(
        onClosing: (){
          widget.callback();
        },
        constraints: const BoxConstraints(minWidth: 1200,maxWidth: 1200),
        title: Row(
          children: [
             Text(pricePart!.name+'数据输入'),
            const SizedBox(width: 50,),
            ViewUtil.doneIcon("保存", (){
              save();
            })
          ],
        ),
        child: ShadForm(
          key: formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [

              Visibility(
                  visible: false,
                  child: Row(children: [
                    Expanded(child:  ShadInputFormField(
                      id: 'name',
                      initialValue: pricePart!.name,
                      label: const Text('型号名称'),
                      placeholder: const Text('请输入型号名称'),
                      validator: (v) {
                        if (v.isEmpty) {
                          return '请输入型号名称';
                        }
                        return null;
                      },
                    ),),
                    const SizedBox(width: 10),
                    Expanded(child: ShadInputFormField(
                      id: 'code',
                      label: const Text('Code'),
                      initialValue: pricePart!.code,
                      placeholder: const Text('请输入Code'),
                      validator: (v) {
                        if (v.isEmpty) {
                          return '请输入Code';
                        }
                        return null;
                      },
                    ),)
                  ],))
              ,
              const SizedBox(height: 16),
              Visibility(
                  visible: false,
                  child:  Row(
                    children: [
                      Expanded(child: ShadInputFormField(
                        id: 'dPrice',
                        label: const Text('单价'),
                        suffix: const Text('元'),
                        initialValue: MathUtil.formatDouble(pricePart!.dPrice, 2),
                        placeholder: const Text('请输入单价'),
                        validator: (v) {
                          if (v.isEmpty) {
                            return '请输入单价';
                          }
                          return null;
                        },
                      ),),
                      const SizedBox(width: 10),
                      Expanded(child: ShadInputFormField(
                        id: 'tax',
                        label: const Text('税点(如8%,则填写0.08）'),
                        suffix: const Text('%'),
                        initialValue: MathUtil.formatDouble(double.parse(pricePart!.tax), 2),
                        placeholder: const Text('请输入税点'),
                        validator: (v) {
                          if (v.isEmpty) {
                            return '请输入税点';
                          }
                          return null;
                        },
                      ),)
                    ],

                  ))
              ,





              Visibility(
                visible: true,
                child:  Text('型号概况',style: TextStyle(color: Colors.black,  fontSize: ViewUtil.fontSize(22)),),),

              Visibility(
                visible: true,
                child:  Wrap(
                  crossAxisAlignment: WrapCrossAlignment.center,
                  runAlignment: WrapAlignment.start,
                  direction: Axis.horizontal, // 水平方向排列（默认）
                  alignment: WrapAlignment.start, // 水平靠左（默认值，可省略）
                  spacing: 10, // 子组件横向间距
                  runSpacing: 0, // 换行后纵向间距
                  children: getRemarkViews(),
                ),),




              const SizedBox(height: 16),
              Visibility(
                visible: true,
                child:  Text('型号参数',style: TextStyle(color: Colors.black,  fontSize: ViewUtil.fontSize(22)),),),

              Visibility(
                visible: true,
                child:  Wrap(
                  crossAxisAlignment: WrapCrossAlignment.center,
                  runAlignment: WrapAlignment.start,
                  direction: Axis.horizontal, // 水平方向排列（默认）
                  alignment: WrapAlignment.start, // 水平靠左（默认值，可省略）
                  spacing: 10, // 子组件横向间距
                  runSpacing: 0, // 换行后纵向间距
                  children: getParmsViews(),
                ),),

              const SizedBox(height: 16),
              Visibility(
                visible: false,
                child: Row(
                  children: [
                    Text('型号说明',style: TextStyle(color: Colors.black,  fontSize: ViewUtil.fontSize(22)),),

                    Expanded(child: Container()),
                    ViewUtil.addIcon('新增型号说明',(){
                      showSpecDialog({"name":"","value":""});
                    }),

                  ],
                ),),


              const SizedBox(height: 16),
              Visibility(
                  visible: false,
                  child:  specView())
              ,
              const SizedBox(height: 16),


              const SizedBox(height: 16),


              // Row(
              //   children: [
              //     Text('参数',style: TextStyle(color: Colors.black,  fontSize: ViewUtil.fontSize(22)),),
              //     Expanded(child: Container()),
              //     ViewUtil.editIcon((){
              //       showShadSheet(
              //         barrierColor: Colors.transparent,
              //         side: ShadSheetSide.right,
              //         context: context,
              //         builder: (context) =>  MaterialParmVC(pricePart:pricePart! , callback: () {
              //           //回调
              //           //getDetail();
              //         },),
              //       );
              //     }),
              //
              //   ],
              // ),
              // ViewUtil.lineView(),
              // const SizedBox(height: 16),
              // Row(
              //   children: [
              //     Text('零件',style: TextStyle(color: Colors.black,  fontSize: ViewUtil.fontSize(22)),),
              //     Expanded(child: Container()),
              //     ViewUtil.editIcon((){
              //       showShadSheet(
              //         barrierColor: Colors.transparent,
              //         side: ShadSheetSide.right,
              //         context: context,
              //         builder: (context) =>   MaterialListVC(pricePart:pricePart! , callback: () {
              //           //回调
              //          // getDetail();
              //         },),
              //       );
              //     }),
              //
              //   ],
              // ),
              // ViewUtil.lineView(),
              // const SizedBox(height: 16),
              // Row(
              //   children: [
              //     Text('单价计算公式(有零件则使用零件累加计算)',style: TextStyle(color: Colors.black, fontSize: ViewUtil.fontSize(22)),),
              //     Expanded(child: Container()),
              //     ViewUtil.editIcon((){
              //       showShadSheet(
              //         barrierColor: Colors.transparent,
              //         side: ShadSheetSide.right,
              //         context: context,
              //         builder: (context) =>  RuleVC(pricePart:pricePart! , callback: () {
              //           //回调
              //           getDetail();
              //         },),
              //       );
              //     }),
              //
              //   ],
              // ),
              // Card(
              //     color: Colors.white,
              //     child:
              //     Container(
              //       padding: const EdgeInsets.only(left: 10,right: 10,top: 5,bottom: 5),
              //       alignment: Alignment.centerLeft,
              //       child: Text(getRuleString(ruleStr),style: const TextStyle(fontSize: 20),),
              //     )),



            ],

          ),

        ),
      );
  }


  List<Widget> getRemarkViews(){
    List<Widget> widgets=[];
    for(PriceParm parm in parmPart.remarkList){
      List selectItems=[];
      if(parm.rule.isNotEmpty){
        List list=jsonDecode(parm!.rule);
        for (var item in list) {
          selectItems.add(item.toString());
        }
      }
      var initValue="";
      if(remarkValues.containsKey(parm.id)){
        initValue=remarkValues[parm.id];
      }else{
        if(parm.value.isNotEmpty){
          initValue=parm.value;
        }
      }

      parm.value=initValue;
      widgets.add(
          SizedBox(width: 370,
              child:
              Row(children: [
                SizedBox(width: 130,child: Text("${parm.name}:",style: TextStyle(color: parm.required==1&&parm.value.isEmpty&&parm.value.isEmpty?Colors.red:Colors.black),),),
                if(parm.type==0)
                  Expanded(child: ShadInput(
                    decoration: ShadDecoration(
                      border: ShadBorder.all(color: parm.required==1&&parm.value.isEmpty&&parm.value.isEmpty?Colors.red:Colors.black ),
                    ),
                    suffix: Text(parm.unit??""),
                    textAlign: TextAlign.end,
                    initialValue:initValue,
                    placeholder: Text("请输入${parm.name}"),
                    onChanged: (value){
                      debugPrint(value);
                      parm.value=value;
                      remarkValues[parm.id]=value;
                      setState(() {

                      });
                    },
                  )),
                if(parm.type==1)
                  Expanded(child:  ShadSelect<String>(

                    decoration: ShadDecoration(
                        border: ShadBorder.all(color: parm.required==1&&parm.value.isEmpty&&parm.value.isEmpty?Colors.red:Colors.black ),
                    ),
                    minWidth: 350,
                    onChanged: (value){
                      if (value != null && parm != null) {  // 增加parm的空判断
                        parm.value = value;  // 移除不必要的toString()
                        remarkValues[parm.id]=value;
                        setState(() {

                        });
                      }
                    },
                    initialValue: initValue,
                    options: selectItems.map((item) {
                      final value = item.isNotEmpty ? item : '';
                      return ShadOption<String>(
                        value: value,
                        child: Text(value),
                      );
                    }).toList(),
                    selectedOptionBuilder: (context, value) {
                      // 处理value可能为null的情况
                      if (value == null || value.isEmpty || value == 'none') {
                        return const Text('请选择');
                      }
                      return Text(value);
                    },
                    placeholder: const Text('请选择'),

                  ),),
                const SizedBox(width: 10,)
              ],)));
    }
    return widgets;
  }


  List<Widget> getParmsViews(){
    List<Widget> widgets=[];
    for(PriceParm parm in parmPart.partParmList){
      List selectItems=[];
      if(parm.rule.isNotEmpty){
        List list=jsonDecode(parm!.rule);
        for (var item in list) {
          selectItems.add(item.toString());
        }
      }
      var initValue="";
      if(parmValues.containsKey(parm.id)){
        initValue=parmValues[parm.id];
      }else{
        if(parm.value.isNotEmpty){
          initValue=parm.value;
        }
      }

      parm.value=initValue;
      widgets.add(
          SizedBox(width: 370,
              child:
              Row(children: [
                SizedBox(width: 130,child: Text("${parm.name}:",style: TextStyle(color: parm.required==1&&parm.value.isEmpty&&parm.value.isEmpty?Colors.red:Colors.black),),),

                if(parm.type==0)
                  Expanded(child: ShadInput(
                    decoration: ShadDecoration(
                      border: ShadBorder.all(color: parm.required==1&&parm.value.isEmpty&&parm.value.isEmpty?Colors.red:Colors.black ),
                    ),
                    suffix: Text(parm.unit??""),
                    textAlign: TextAlign.end,
                    initialValue:initValue,
                    placeholder: Text("请输入${parm.name}"),
                    onChanged: (value){
                      debugPrint(value);
                      parm.value=value;
                      parmValues[parm.id]=value;
                      setState(() {

                      });
                    },
                  )),
                if(parm.type==1)
                  Expanded(child:  ShadSelect<String>(
                    minWidth: 350,
                    decoration: ShadDecoration(
                      border: ShadBorder.all(color: parm.required==1&&parm.value.isEmpty&&parm.value.isEmpty?Colors.red:Colors.black ),
                    ),
                    onChanged: (value){
                      if (value != null && parm != null) {  // 增加parm的空判断
                        parm.value = value;  // 移除不必要的toString()
                        parmValues[parm.id]=value;
                        setState(() {

                        });
                      }
                    },
                    initialValue: initValue,
                    options: selectItems.map((item) {
                      final value = item.isNotEmpty ? item : '';
                      return ShadOption<String>(
                        value: value,
                        child: Text(value),
                      );
                    }).toList(),
                    selectedOptionBuilder: (context, value) {
                      // 处理value可能为null的情况
                      if (value == null || value.isEmpty || value == 'none') {
                        return const Text('请选择');
                      }
                      return Text(value);
                    },
                    placeholder: const Text('请选择'),

                  ),),
                const SizedBox(width: 10,)
              ],)));
    }
    return widgets;
  }


  getRuleString(var rule){
    var ruleStr="";
    if(rule.isNotEmpty){
      List<dynamic> list = json.decode(rule);

      for(var item in list){
        PriceRule rule=PriceRule.fromJson(item);
        if(rule.handle==0){
          ruleStr="$ruleStr${rule.value}";
        }else{
          ruleStr="$ruleStr${rule.name}";
        }
      }
    }
    if(ruleStr.isEmpty)ruleStr="未设置";

    return ruleStr;
  }


  Widget specView(){

    final double tableHeight = _calculateTableHeight(specsList.length);
    return // 表格（高度固定为计算值）
      Padding(
        padding: EdgeInsets.symmetric(horizontal: _outerPadding),
        child: Container(
          // 应用计算出的高度
          height: tableHeight,
          decoration: BoxDecoration(
            border: Border.all(color: Colors.grey[200]!, width: _borderWidth),
            borderRadius: BorderRadius.circular(8),
          ),
          child: DataTable2(
            columnSpacing: 12,
            //  minWidth: MediaQuery.of(context).size.width - 2 * _outerPadding,
            minWidth: 500,
            headingRowHeight: _headerHeight - 2 * _borderWidth, // 减去边框占用高度
            dataRowHeight: _rowHeight - 2 * _borderWidth, // 减去边框占用高度
            // 表头
            columns: const [
              DataColumn2(
                label: Text('  操作'),
                fixedWidth: 140,
              ),
              DataColumn2(
                label: Text('名称'),
                size: ColumnSize.L,

              ),
              DataColumn2(
                label: Text('参数'),
                size: ColumnSize.L,
              ),
            ],

            // 表格内容（行高固定）
            rows: specsList.map((item) {
              return DataRow(cells: [
                DataCell(
                  Row(
                    children: [

                      ViewUtil.editIcon('编辑规格',(){showSpecDialog(item);}),

                      ViewUtil.delIcon('删除规格',(){
                        specsList.remove(item);
                        setState(() {

                        });
                      }),

                    ],
                  ),
                ),
                DataCell(Padding(
                  padding: const EdgeInsets.symmetric(vertical: 12),
                  child: Text(item["name"]),
                )),

                DataCell(Padding(
                  padding: const EdgeInsets.symmetric(vertical: 12),
                  child: Text(item["value"]),
                )),

              ]);
            }).toList(),
          ),
        ),
      );
  }

  // 固定高度参数（可根据需求调整）
  final double _headerHeight = 56; // 表头高度（含内边距）
  final double _rowHeight = 48; // 每行高度（含内边距）
  final double _borderWidth = 1; // 边框宽度
  final double _outerPadding = 10; // 表格外间距

  // 计算表格总高度的核心方法
  double _calculateTableHeight(int length) {
    // 总高度 = 表头高度 + 数据行总高度 + 边框总高度
    // 边框高度：上下边框（2条）+ 行之间的分隔线（数据行数-1条）
    final int borderCount = 2 + (length - 1);
    final double totalBorderHeight = borderCount * _borderWidth;

    return _headerHeight + // 表头高度
        (_rowHeight * length) + // 所有数据行高度
        totalBorderHeight; // 边框总高度
  }



  void showSpecDialog(var item){
    showShadDialog(context: context, builder: (context)=>
        ShadDialog(
            actions: [ShadButton(child: const Text('确定'),onPressed: (){
              if (dialogKey.currentState!.saveAndValidate()) {
                var values = dialogKey.currentState!.value;
                var name=values["name"];
                var value=values["value"];
                if(item["name"].length==0){
                  item["name"]=name;
                  item["value"]=value;
                  specsList.add(item);

                }else{
                  item["name"]=name;
                  item["value"]=value;
                }
                setState(() {

                });
                Navigator.pop(context);
              }
            },)],
            child:
            ShadForm(
              key: dialogKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  ShadInputFormField(
                    id: 'name',
                    initialValue: item["name"],
                    label: const Text('规格名称'),
                    placeholder: const Text('请输入规格名称'),
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入规格名称';
                      }
                      return null;
                    },
                  ),
                  const SizedBox(height: 16),
                  ShadInputFormField(
                    id: 'value',
                    initialValue: item["value"],
                    label: const Text('规格'),
                    placeholder: const Text('请输入规格'),
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入规格';
                      }
                      return null;
                    },
                  )


                ],
              )

              ,)

        )
    );
  }


  void save(){
    if (formKey.currentState!.saveAndValidate()) {

      // if(specsList.isEmpty){
      //   ToastUtil.showToast("请添加规格");
      //   return;
      // }

      bool result=true;
      var remarkDatas=[];
      for(PriceParm parm in parmPart.remarkList){
        var value=parm.value;
        // if(parm.required==1&&value.isEmpty){
        //   result=false;
        //   if(parm.type==0){
        //     ToastUtil.showToast('请输入${parm.name}');
        //   }else{
        //     ToastUtil.showToast('请选择${parm.name}');
        //   }
        //
        //   break;
        // }else{
        //   remarkDatas.add({"name":parm.id,"value":value});
        // }
        remarkDatas.add({"name":parm.id,"value":value});
      }
      if(!result){
        return;
      }

      var parmDatas=[];
      for(PriceParm parm in parmPart.partParmList){
        var value=parm.value;
        // if(parm.required==1&&value.isEmpty){
        //   result=false;
        //   if(parm.type==0){
        //     ToastUtil.showToast('请输入${parm.name}');
        //   }else{
        //     ToastUtil.showToast('请选择${parm.name}');
        //   }
        //   break;
        // }else{
        //   parmDatas.add({"name":parm.id,"value":value});
        // }
        parmDatas.add({"name":parm.id,"value":value});
      }
      if(!result){
        return;
      }


      var values = formKey.currentState!.value;
      var name=values["name"];
      var code=values["code"];
      var dPrice=values["dPrice"];
      var tax=values["tax"];

      String jsonString = jsonEncode(specsList);
      var parm={
        "name":widget.pricePart.name,
        "code":widget.pricePart.code,
        "spec":widget.pricePart.spec,
        "parentId":widget.pricePart.parentId,
        "id":widget.pricePart.id,
        "dPrice":widget.pricePart.dPrice,
        "tax":widget.pricePart.tax,
        "remark":remarkDatas,
        "parm":parmDatas,
        "serialId":widget.pricePart.serialId,
      };
      BaseRequest.postHttp("price/editmatterialremark",parameters: parm, canTip: true, context: context, onSuccess: (data){
        bool result=BaseRequest.chekResponse(data, true);
        if(result){
          ToastUtil.showToast("编辑成功");
          eventBus.fire(EventRefreshBase());
          Navigator.pop(context);
        }
      }, onError: (error){

      });

    }
  }
}
